<template>
  <div class="admin-container">
    <admin-header />
    <admin-sidebar />
    <div class="admin-main">
      <div class="admin-content">
        <h1>用户管理</h1>
        
        <!-- 搜索过滤区域 -->
        <el-card class="filter-card">
          <el-form :inline="true" :model="filterForm">
            <el-form-item label="用户名">
              <el-input v-model="filterForm.username" placeholder="请输入用户名" clearable />
            </el-form-item>
            <el-form-item label="角色">
              <el-select v-model="filterForm.role" placeholder="请选择角色" clearable>
                <el-option label="全部" value="" />
                <el-option label="管理员" value="admin" />
                <el-option label="普通用户" value="user" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
                <el-option label="全部" value="" />
                <el-option label="正常" value="active" />
                <el-option label="禁用" value="disabled" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <!-- 用户表格区域 -->
        <el-card>
          <div class="table-toolbar">
            <el-button type="primary" @click="showAddDialog">
              <el-icon><plus /></el-icon>
              添加用户
            </el-button>
            <el-button 
              type="danger" 
              :disabled="selectedUsers.length === 0" 
              @click="handleBatchDelete"
            >
              <el-icon><delete /></el-icon>
              批量删除
            </el-button>
          </div>
          
          <el-table
            :data="userList"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange"
            v-loading="loading"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="ID" width="80" sortable />
            <el-table-column prop="username" label="用户名" width="150" />
            <el-table-column prop="email" label="邮箱" width="200" />
            <el-table-column prop="phone" label="手机号" width="150" />
            <el-table-column prop="role" label="角色" width="120">
              <template #default="{row}">
                <el-tag :type="row.role === 'admin' ? 'danger' : 'primary'">
                  {{ row.role === 'admin' ? '管理员' : '普通用户' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{row}">
                <el-switch
                  v-model="row.status"
                  active-value="active"
                  inactive-value="disabled"
                  @change="handleStatusChange(row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="注册时间" width="180" sortable />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{row}">
                <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              :total="pagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>
    
    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form
        :model="userForm"
        :rules="rules"
        ref="userFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="isAdd">
          <el-input 
            v-model="userForm.password" 
            type="password" 
            placeholder="请输入密码" 
            show-password
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="userForm.role">
            <el-radio label="admin">管理员</el-radio>
            <el-radio label="user">普通用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio label="active">正常</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUserForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import AdminHeader from '@/components/admin/AdminHeader.vue'
import AdminSidebar from '@/components/admin/AdminSidebar.vue'

// 模拟数据
const mockUsers = Array.from({ length: 50 }, (_, i) => ({
  id: i + 1,
  username: `user${i + 1}`,
  email: `user${i + 1}@example.com`,
  phone: `138${Math.random().toString().slice(2, 6)}${Math.random().toString().slice(2, 6)}`,
  role: Math.random() > 0.8 ? 'admin' : 'user',
  status: Math.random() > 0.2 ? 'active' : 'disabled',
  createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toLocaleString()
}))

// 搜索表单
const filterForm = reactive({
  username: '',
  role: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 用户列表
const userList = ref([])
const loading = ref(false)
const selectedUsers = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(false)
const userFormRef = ref(null)
const userForm = reactive({
  id: '',
  username: '',
  password: '',
  email: '',
  phone: '',
  role: 'user',
  status: 'active'
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 初始化加载数据
onMounted(() => {
  fetchUsers()
})

// 获取用户列表
const fetchUsers = () => {
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    // 过滤数据
    const filtered = mockUsers.filter(user => {
      return (
        (filterForm.username ? user.username.includes(filterForm.username) : true) &&
        (filterForm.role ? user.role === filterForm.role : true) &&
        (filterForm.status ? user.status === filterForm.status : true))
    })
    
    // 分页
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    userList.value = filtered.slice(start, end)
    pagination.total = filtered.length
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchUsers()
}

// 重置搜索
const resetSearch = () => {
  filterForm.username = ''
  filterForm.role = ''
  filterForm.status = ''
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchUsers()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchUsers()
}

// 选择用户变化
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 显示添加用户对话框
const showAddDialog = () => {
  dialogTitle.value = '添加用户'
  isAdd.value = true
  resetUserForm()
  dialogVisible.value = true
}

// 显示编辑用户对话框
const showEditDialog = (user) => {
  dialogTitle.value = '编辑用户'
  isAdd.value = false
  Object.assign(userForm, user)
  dialogVisible.value = true
}

// 重置用户表单
const resetUserForm = () => {
  userForm.id = ''
  userForm.username = ''
  userForm.password = ''
  userForm.email = ''
  userForm.phone = ''
  userForm.role = 'user'
  userForm.status = 'active'
}

// 提交用户表单
const submitUserForm = () => {
  userFormRef.value.validate(valid => {
    if (valid) {
      // 模拟API请求
      setTimeout(() => {
        if (isAdd.value) {
          // 添加用户
          const newUser = {
            ...userForm,
            id: mockUsers.length + 1,
            createTime: new Date().toLocaleString()
          }
          mockUsers.unshift(newUser)
          ElMessage.success('添加用户成功')
        } else {
          // 更新用户
          const index = mockUsers.findIndex(u => u.id === userForm.id)
          if (index !== -1) {
            mockUsers[index] = { ...mockUsers[index], ...userForm }
            ElMessage.success('更新用户成功')
          }
        }
        dialogVisible.value = false
        fetchUsers()
      }, 500)
    }
  })
}

// 删除用户
const handleDelete = (user) => {
  ElMessageBox.confirm(`确定要删除用户 "${user.username}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟API请求
    setTimeout(() => {
      const index = mockUsers.findIndex(u => u.id === user.id)
      if (index !== -1) {
        mockUsers.splice(index, 1)
        ElMessage.success('删除用户成功')
        fetchUsers()
      }
    }, 300)
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedUsers.value.length === 0) return
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedUsers.value.length} 个用户吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟API请求
    setTimeout(() => {
      const ids = selectedUsers.value.map(u => u.id)
      for (let i = mockUsers.length - 1; i >= 0; i--) {
        if (ids.includes(mockUsers[i].id)) {
          mockUsers.splice(i, 1)
        }
      }
      selectedUsers.value = []
      ElMessage.success(`成功删除 ${ids.length} 个用户`)
      fetchUsers()
    }, 300)
  }).catch(() => {})
}

// 状态变更
const handleStatusChange = (user) => {
  // 模拟API请求
  setTimeout(() => {
    const index = mockUsers.findIndex(u => u.id === user.id)
    if (index !== -1) {
      mockUsers[index].status = user.status
      ElMessage.success(`用户状态已${user.status === 'active' ? '启用' : '禁用'}`)
    }
  }, 300)
}
</script>

<style scoped>
.admin-container {
  position: relative;
  height: 100vh;
  overflow: hidden;
}

.admin-main {
  margin-left: 220px;
  padding-top: 60px;
  height: 100%;
  overflow-y: auto;
  background-color: #f0f2f5;
}

.admin-content {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-toolbar {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>